<template>

	<view class="container">
		<view>
			<up-alert title="点击自己头像可以修改昵称,点击别人头像可以转积分" type="warning" :closable="true"
				:description="description"></up-alert>

		</view>
		<!---顶部样式-->
		<view class="head-container">
			<view class="head-item" @click="houseShardingCodeModelShow">
				<text class="head-label">添加玩家</text>
				<up-icon name="plus-circle" size="20"></up-icon>
			</view>
			<view class="head-item" @click="changeHouse">
				<text class="head-label">转让房主</text>
				<up-icon name="home" size="20"></up-icon>
			</view>
			<view class="head-item" @click="refreshHouseInfo">
				<text class="head-label">刷新房间</text>
				<up-icon name="reload" size="20"></up-icon>
			</view>
		</view>
		<view class="avatar-scroll-container">

			<!-- 横向滚动区域 -->
			<scroll-view class="avatar-scroll" :scroll-x="true" :show-scrollbar="false" :enhanced="true">
				<!-- 头像列表 -->
				<view class="avatar-list">
					<view v-for="(user, index) in userList" :key="index" @click="showRewardModal(user)"
						class="avatar-item">

						<!-- 外层容器，用于定位 -->
						<view class="avatar-wrapper" v-if="user.imgUrl">
							<up-avatar :src="user.imgUrl" size="40" customStyle="margin: 0 10rpx"></up-avatar>

							<!-- 右上角标签 -->
							<text class="badge-text">
								{{user.houseRoleTypeDes}}
							</text>
						</view>
						<view class="avatar-wrapper" v-if="!user.imgUrl">
							<up-avatar :text="user.nickName?.charAt(0).toUpperCase()" size="40"
								customStyle="margin: 0 10rpx"></up-avatar>

							<!-- 右上角标签 -->
							<text class="badge-text">
								{{user.houseRoleTypeDes}}
							</text>
						</view>


						<!-- 昵称和分数 -->
						<view class="user-info">
							<text class="nickname">{{ user.nickName }}</text>
							<text class="score">{{ user.score }}</text>
						</view>
					</view>

				</view>
				<!-- 			<u-avatar v-for="(user, index) in userList" :key="index" :src="user.imgUrl" size="40"
					customStyle="margin: 0 10rpx" @click="showRewardModal(user)">
					<!-- 如果没有头像，显示用户名首字母 -->
				<!-- 	<template v-if="!user.imgUrl">
						{{ user.nickName?.charAt(0).toUpperCase() }}
					</template>
					<u--text :text="user.score" size="14" color="#303133" />
				</u-avatar> -->

			</scroll-view>
		</view>



		<!-- 历史近10个积分记录 -->
		<view class="log-container">
			<!-- 日志项 -->
			<view v-for="(log, index) in logList" :key="index" class="log-item">
				<text class="user-action">{{log.title}}</text>
				<text class="change-value">{{log.content}}</text>
			</view>
		</view>
		<view class="footer-contaner">
			<view class="footer-btn-group">
				<view class="footer-btn footer-cancel-btn" @click="goScoreRecord">
					<text class="footer-btn-text">给分记录</text>
				</view>
				<view class="footer-btn footer-confirm-btn" @click="closeHouse">
					<text class="footer-btn-text">结算房间</text>
				</view>
			</view>
		</view>
	</view>


	<!-- 积分奖励弹窗 -->
	<u-modal :show="showModal" :title="modalTitle" confirmText="确认" @confirm="onConfirm" @close="onCancel"
		@cancel="onCancel" closeOnClickOverlay="true" showConfirmButton="true" showCancelButton="true"
		:custom-style="{ top: '10%' }">
		<up-input placeholder="请输入积分" v-model="transferScore" @change="change" typ="number"></up-input>
	</u-modal>


	<uEditUserInfoModel ref="editUserModel" title="修改资料" @confirm="onEditUserConfirm" />


	<uHouseShardingCodeModel ref="houseShardingCodeModel" />
</template>

<script setup>
	import {
		onMounted,
		ref
	} from 'vue';

	import {
		onShow,
		onLoad,
		onUnload,
		onShareAppMessage
	} from '@dcloudio/uni-app'

	import {
		getHouseQrCodeRequest,
		getHouseInfoRequest,
		transferAddScoreRequest,
		transferReduceScoreRequest,
		joinHouseRequest,
		getHouseNoticePageRequest,
		closeHouseRequest
	} from '@/request/house.js'

	import uEditUserInfoModel from '@/components/u-edit-userinfo-model/index.vue'
	import uHouseShardingCodeModel from '@/components/u-house-sharding-code-model/index.vue'
	// import hasToken from '@/utils/usertoken.js'
	import wxJsCodeLogin from '@/utils/buzlogin.js'
	import webconst from '@/utils/webconst.js'
	import {
		goToInternalPage
	} from '@/utils/jump.js'
	import {
		connectWebSocket,
		sendMessage,
		closeWebSocket
	} from '@/utils/socket.js'
	onMounted(() => {


	})
	
	
	// 页面生命周期（uni-app）
	onLoad((option) => {
		if (option.id) {
			//是否有分享用户
			//1.判断进入的用户和分享的用户是否同一个人
			//2.判断新登录的用户是否注册、没注册就要注册
			//3.判断这个用户是否加入过这个房间，如果没有则加入
			shareHouseId.value=option.id
			console.log(option.share);
			console.log(option.shareUserCode);
			wxJsCodeLogin()
				.then((loginType) => {

					//jscode
					joinHouse(option.id)
			})

		} else {
			houseCode.value=option.code;
			var code = option.code;
			//进入页面默认调用登录
			initHouseInfo(code, true)

		}
	})
	const lastRefreshDate = ref(null);
	const refreshHouseInfo = () => {
		 const now = Date.now(); // 当前时间戳（毫秒）
		if (lastRefreshDate.value != null) {
			const diff = now - lastRefreshDate.value;
			
			//查看上次时间
			if (diff < 2 * 60 * 1000) {
				uni.showToast({
					title: "刷新频率太高了！",
					icon: 'error',
					duration: 1500
				})
				return;
			}
		}
		uni.showToast({
			title: "刷新成功！",
			icon: 'none',
			duration: 1500
		})
        lastRefreshDate.value=now;
		getHouseInfo(houseCode.value, false, true)
		
	}

	//关闭token
	onUnload(() => {
		closeWebSocket();
	})
	//初始化房间信息
	const initHouseInfo = (code, isFirst) => {
		//进入页面默认调用登录
		getHouseInfo(code, isFirst, true)
	}

	const joinHouse = (id) => {

		joinHouseRequest({
			"id": id
		}).then((res) => {
			//这里得返回code了
			initHouseInfo(res.data, true);
			console.log('成功', res);
		}).catch((err) => {
			console.error('失败', err);
		});
	}

	const qrCodeShow = ref(false);
	const qrCodeSrc = ref(null);
	//获取房间二维码code
	const getHouseQrCode = (code) => {
		getHouseQrCodeRequest({
			"code": code
		}).then((res) => {
			if (res.code == 0) {
				qrCodeShow.value = true;
				qrCodeSrc.value = webconst.img_prefix + res.data.sharingQrCodeImg;
			}
			console.log('成功', res);
		}).catch((err) => {
			console.error('失败', err);
		});
	}
	const shareHouseId = ref(0)
	const houseCode = ref('')
	const houseNumber = ref('')
	const houseId = ref(0)
	const currrentUserCode = ref('')
	const currrentUserNickName = ref('')
	//获取房间二维码code
	const getHouseInfo = (code, isFirst, isNotice) => {
		getHouseInfoRequest({
			"code": code
		}).then((res) => {
			if (res.code == 0) {
				userList.value = res.data.userInfos
				houseCode.value = res.data.houseCode
				houseId.value = res.data.houseId
				houseNumber.value = res.data.houseNumber
				currrentUserCode.value = res.data.userCode
				res.data.userInfos.map(user => {
					if (user.userCode == currrentUserCode.value) {
						currrentUserNickName.value = user.nickName;
					}
				});
				if (isFirst) {
					connectWebSocket(code, currrentUserCode.value, currrentUserNickName.value, receviedMessage)
					houseShardingCodeModelShow(code);

				}
				if (isNotice) {
					getHouseNoticeInfo(code);
				}
			}
			console.log('成功', res);
		}).catch((err) => {
			console.error('失败', err);
		});
	}

	//执行消息后执行
	const receviedMessage = (type, message, data) => {
		setTimeout(() => {
			console.log("recevied message type" + type)
			//判断消息类型
			if (type == "notice") {
				// 触发全局事件或 Vuex 提交
				uni.showToast({
					title: message,
					duration: 2000,
					icon: 'none', // 不显示图标
					position: 'bottom' // 显示在底部
				});
				goToInternalPage("usercenter/index")
			} else {

				getHouseInfo(houseCode.value, false, true);
			}
		}, 1000)

	}

	// 模拟用户数据
	const userList = ref([])


	// 控制弹窗显示
	const showModal = ref(false)

	const modalTitle = ref('转积分')
	const transferUser = ref('') //转账用户
	const transferScore = ref(0) //转账积分
	// 显示奖励弹窗
	const showRewardModal = (user) => {
		//如果是自己 就弹修改图片的弹窗
		if (currrentUserCode.value == user.userCode) {
			editUserModelShow();
			//houseShardingCodeModelShow()
			return;
		}
		transferScore.value = 0;
		transferUser.value = user.userCode;
		showModal.value = true

	}

	// 确认按钮回调
	const onConfirm = () => {
		if (transferScore.value == "") {
			uni.showToast({
				title: `请输入积分`,
				icon: 'error',
				duration: 2000
			})
			return;
		}
		if (transferScore.value == 0) {
			uni.showToast({
				title: `积分不能为0`,
				icon: 'error',
				duration: 2000
			})
			return;
		}
		if (transferScore.value >= 10000000) {
			uni.showToast({
				title: `输入数字过大`,
				icon: 'error',
				duration: 2000
			})
			return;
		}
		if (transferScore.value <= -10000000) {
			uni.showToast({
				title: `输入数字过小`,
				icon: 'error',
				duration: 2000
			})
			return;
		}
		if (transferScore.value >= 0) {
			transferAddScore();
		} else {
			transferReduceScore();
		}
	}

	const onCancel = () => {
		showModal.value = false
	}


	//转积分
	const transferAddScore = () => {
		transferAddScoreRequest(houseCode.value, transferScore.value, transferUser.value).then((res) => {
			if (res.code == 0) {
				sendMessage({
					opration: 1
				})
				getHouseInfo(houseCode.value, false, true)



			} else {
				uni.showToast({
					title: res.message,
					icon: 'error',
					duration: 2000
				})
			}
			showModal.value = false
			console.log('成功', res);
		}).catch((err) => {
			console.error('失败', err);
		});
	}

	//扣减用户积分
	const transferReduceScore = (code) => {
		transferReduceScoreRequest(houseCode.value, transferScore.value, transferUser.value).then((res) => {
			if (res.code == 0) {

				getHouseInfo(houseCode.value, false, true)
				sendMessage({
					opration: 1
				})

			} else {
				uni.showToast({
					title: res.message,
					icon: 'error',
					duration: 2000
				})
			}
			showModal.value = false
			console.log('成功', res);
		}).catch((err) => {
			console.error('失败', err);
		});
	}

	const editUserModel = ref(null)

	const editUserModelShow = async () => {
		try {
			await editUserModel.value.open({
				code: houseCode.value
			})
			console.log('用户点击了确定')
		} catch (err) {
			console.log(err)
			console.log('用户点击了取消')
		}
	}
	//确认后可以要重新加载一下房间信息
	const onEditUserConfirm = (data) => {
		sendMessage({
			opration: 0
		})
		initHouseInfo(houseCode.value)
	}

	const houseShardingCodeModel = ref(null)
	const houseShardingCodeModelShow = async () => {
		try {
			await houseShardingCodeModel.value.open({
				code: houseCode.value,
				houseNumber: houseNumber.value
			})
			console.log('用户点击了确定')
		} catch (err) {
			console.log(err)
			console.log('用户点击了取消')
		}
	}



	//分享链接相关
	onShow(() => {
        if (shareHouseId.value!=0) {
        	wxJsCodeLogin()
        		.then((loginType) => {
        			joinHouse(shareHouseId.value)
        	})
        
        } else {        
        	//进入页面默认调用登录
        	initHouseInfo(houseCode.value, true)
        
        }
		uni.showShareMenu({
			withShareTicket: true,
			// 显示分享到聊天、朋友圈
			showShareItems: ['shareAppMessage']
		})
	})

	//手动分享
	const onHandleShare = () => {
		uni.showShareMenu({
			withShareTicket: true,
			success: () => {
				console.log('分享菜单已打开')
			},
			fail: (err) => {
				console.error('拉起分享失败', err)
			}
		})
	}


	onShareAppMessage(() => {
		console.log('分享被调用了') // 看微信开发者工具控制台
		console.log(webconst.share_house_info.title)
		//houseId.value
		//const path = webconst.share_house_info.path + "?id=" + 18;
		const path = webconst.share_house_info.path + "?id=" + houseId.value;
		console.log(path)
		return {
			title: webconst.share_house_info.title+"--邀请你加入"+houseNumber.value+"房间",
			path: path,
			imageUrl: webconst.share_house_info.imageUrl
		}
	})



	// 模拟日志记录
	const logList = ref([])


	//获取房间通知信息
	const getHouseNoticeInfo = (code) => {
		getHouseNoticePageRequest({
			"houseCode": code,
			"pageNumber": 1,
			"rowsPerPage": 5,
		}).then((res) => {
			if (res.code == 0) {
				logList.value = res.rows
			}
			console.log('成功', res);
		}).catch((err) => {
			console.error('失败', err);
		});
	}


	// 关闭房间信息
	const closeHouse = () => {
		//获取房间数据
		closeHouseRequest({
			"code": houseCode.value
		}).then((res) => {
			if (res.code == 0) {
				sendMessage({
					opration: 2
				})
				uni.showToast({
					type: 'success',
					title: `关闭房间`,
					icon: 'none'
				})
				goToInternalPage("usercenter/index")

			} else {
				uni.showToast({
					title: res.message,
					icon: 'error',
					duration: 2000
				})
			}
			console.log('成功', res.message);
		}).catch((err) => {
			console.error('失败', err);
		});
	}
	const goScoreRecord = () => {
		//关闭websocket
		closeWebSocket();
		goToInternalPage("housescorerecord/index?code=" + houseCode.value)
	}

	const changeHouse = () => {
		uni.showToast({
			title: "暂时在开发中",
			icon: 'error',
			duration: 2000
		})
	}
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		position: relative;
		/* 关键：为固定定位提供参照 */
	}


	//头部样式区
	.head-container {
		display: flex;


		justify-content: center;
		/* 关键：容器内容居中 */
		padding: 10px;
		background-color: #ffffff;
		border-bottom: 1px solid #eee;
	}

	.head-item {
		display: flex;
		justify-content: center;
		/* 关键：文字和图标在item内水平居中 */
		align-items: center;
		/* 关键：垂直居中 */
		gap: 2px;
		/* 文字和图标之间的间距 */
		padding: 8px 5px;


		margin: 0 10px;
		/* 两个item之间的间距 */
	}

	.head-label {
		font-size: 14px;
		margin-right: 3px;
	}



	//用户信息
	.avatar-scroll-container {
		padding: 20rpx 30rpx;
		background-color: #ffffff;
	}

	.title {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
		font-weight: 500;
	}

	.avatar-scroll {
		white-space: nowrap; // 防止换行
		width: 100%;
		height: 220rpx;
		/* 可选：添加内边距或滚动条样式 */
	}

	.avatar-list {
		display: inline-flex;
		align-items: center;
		height: 100%;
		padding: 10rpx 0;
	}

	.avatar-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		text-align: center;
		width: 150rpx;
		/* 可选：固定宽度控制布局 */
	}

	/* 外层容器 */
	.avatar-wrapper {
		position: relative;
		display: inline-flex;
		/* 确保大小包裹头像 */
	}

	/* 标签样式 - 右上角 */
	.badge-text {
		position: absolute;
		top: 0;
		right: 0;
		transform: translate(25%, -25%);
		/* 微调，让标签部分超出头像 */

		/* 视觉样式 */
		background-color: #ff9800;
		/* 橙色背景 */
		color: white;
		font-size: 20rpx;
		font-weight: bold;
		padding: 2rpx 8rpx;
		border-radius: 6rpx;
		border: 1px solid white;

		/* 提高层级，确保在头像之上 */
		z-index: 10;
	}

	user-info {
		font-size: 18rpx;
		margin-top: 8rpx;
		line-height: 1.2;
	}

	.nickname {
		display: block;
		font-weight: 500;
		color: #333;
		max-width: 100rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.score {
		display: block;
		color: orange;
	}


	.reward-content {
		text-align: center;
		padding: 40rpx 0;
	}

	.points-text {
		font-size: 48rpx;
		font-weight: bold;
		color: #ffae00;
		margin: 20rpx 0;
	}

	.desc {
		color: #999;
		font-size: 28rpx;
	}


	//图片处理
	.qrcode-container {
		display: flex;
		justify-content: center;
		/* 水平居中 */
		align-items: center;
		/* 垂直居中 */
		width: 100%;
		margin-top: 50px;

		.qrcode-container-images {
			width: 200px;
			height: 200px;
		}

	}


	/* 整体容器 */
	.log-container {
		padding: 20rpx;
	}

	/* 单个日志项 */
	.log-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;
		font-size: 24rpx;
		color: #333;
	}

	/* 最后一项去掉下边框 */
	.log-item:last-child {
		border-bottom: none;
	}

	/* 用户操作文本颜色 */
	.user-action {
		color: #f56c6c;
		/* 橙色 */
		font-weight: bold;
	}

	/* 变更值文本颜色 */
	.change-value {
		color: #f56c6c;
		font-weight: bold;
	}



	//底部功能
	.footer-contaner {
		position: fixed;
		/* 关键：固定定位 */
		bottom: 0;
		left: 0;
		right: 0;
		padding: 15px 20px;
		background-color: #fff;
		border-top: 1px solid #eee;
		z-index: 100;
		/* 确保在内容之上 */
	}

	.footer-btn-group {
		display: flex;
		justify-content: center;
		gap: 15px;
	}

	.footer-btn {
		flex: 1;
		border-radius: 20px;
		height: 40px;
		line-height: 40px;
		font-size: 16px;
		text-align: center;
		margin: 0 5px;
	}

	.footer-cancel-btn {
		background-color: #f5f5f5;
		color: #333;
	}

	.footer-confirm-btn {
		background-color: #007aff;
		color: #fff;
	}
</style>